package com.king.configuration.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.king.constant.ResponseStatus;
import com.king.pojo.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 浏览器登录失败之后处理器
 *
 * @author liukai
 */
public class BrowserAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        AjaxResult ajaxResult = null;
        if (exception instanceof BadCredentialsException) {
            ajaxResult = new AjaxResult(ResponseStatus.AUTHENTICATION_FAIL);
        }
        String content = objectMapper.writeValueAsString(ajaxResult);

        PrintWriter writer = response.getWriter();
        writer.write(content);
        writer.close();
    }


}
